package com.zbkj.crmeb.chant.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.crmeb.chant.model.ChannelMerchantDistribution;
import com.zbkj.crmeb.chant.dao.ChannelMerchantDistributionDao;
import com.zbkj.crmeb.chant.request.DistributionBaseRebateRequest;
import com.zbkj.crmeb.chant.request.DistributionRequest;
import com.zbkj.crmeb.chant.response.DistributionResponse;
import com.zbkj.crmeb.chant.service.ChannelMerchantDistributionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.crmeb.merchant.admin.service.MerStoreProductService;
import com.zbkj.crmeb.store.response.StoreProductResponse;
import com.zbkj.crmeb.user.model.User;
import com.zbkj.crmeb.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 商户分销模式表 服务实现类
 * </p>
 *
 * @author wuzp
 * @since 2022-04-01
 */
@Service
public class ChannelMerchantDistributionServiceImpl extends ServiceImpl<ChannelMerchantDistributionDao, ChannelMerchantDistribution> implements ChannelMerchantDistributionService {

    @Autowired
    UserService userService;
    @Autowired
    private MerStoreProductService merStoreProductService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean installDistribution(Integer merId, DistributionRequest request) {
        LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //分销员状态自动改为“开启”状态；如果手动关闭则需要商户手动开启才可生效；
        lambdaUpdateWrapper.set(User::getIsPromoter,true)
                .set(User::getPromoterTime,new Date())
                .eq(User::getMerId,merId)
                .eq(User::getIsPromoter,false);
        ChannelMerchantDistribution merchantDistribution = this.getOne(Wrappers.<ChannelMerchantDistribution>lambdaQuery().eq(ChannelMerchantDistribution::getMerId, merId));
        if(merchantDistribution == null){
            merchantDistribution = new ChannelMerchantDistribution();
            BeanUtils.copyProperties(request,merchantDistribution);
            merchantDistribution.setMerId(merId);
            if (null != request.getSpecifyConditions()) {
                merchantDistribution.setSpecifyConditions(request.getSpecifyConditions().toJSONString());
            }
            this.save(merchantDistribution);
            if(request.getModel() == 1){
                userService.update(lambdaUpdateWrapper);
            }
        }else {
            //分销模式变化
            if(!Objects.equals(request.getModel(), merchantDistribution.getModel())){
                // 指定 --> 人人
                if(request.getModel() == 1){
                    //修改该商户下所有用户成推广人,分销员状态自动改为“开启”状态；
                    lambdaUpdateWrapper.setSql("distributor_flag = CASE WHEN distributor_flag IS NULL THEN 1 ELSE distributor_flag END ");
                    userService.update(lambdaUpdateWrapper);
                }else if (merchantDistribution.getModel() != 1){
                    // 指定金额 --> 指定订单
                    if(request.getModel() == 2){
                        lambdaUpdateWrapper.ge(User::getDistributionOrders,request.getCondition().intValue());
                    }else {
                        // 指定订单 --> 指定金额
                        lambdaUpdateWrapper.ge(User::getDistributionPrice,request.getCondition());
                    }
                    userService.update(lambdaUpdateWrapper);
                }
            }else {
                //条件变化
                if(request.getModel() != 1 && request.getCondition().compareTo(merchantDistribution.getCondition())<0){
                    //修改达成条件的用户
                    if(request.getModel() == 2){
                        lambdaUpdateWrapper.ge(User::getDistributionOrders,request.getCondition().intValue());
                        userService.update(lambdaUpdateWrapper);
                    }else if (request.getModel() == 3){
                        lambdaUpdateWrapper.ge(User::getDistributionPrice,request.getCondition());
                        userService.update(lambdaUpdateWrapper);
                    }
                }
                // 指定 --> 人人
                if(request.getModel() == 1){
                    //修改该商户下所有用户成推广人,分销员状态自动改为“开启”状态；
                    lambdaUpdateWrapper.setSql("distributor_flag = CASE WHEN distributor_flag IS NULL THEN 1 ELSE distributor_flag END ");
                    userService.update(lambdaUpdateWrapper);
                }
            }
            BeanUtils.copyProperties(request,merchantDistribution);
            if (null != request.getSpecifyConditions()) {
                merchantDistribution.setSpecifyConditions(request.getSpecifyConditions().toJSONString());
            }
            this.updateById(merchantDistribution);
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean baseRebateRateUpdate(Integer merId, DistributionBaseRebateRequest request) {

        ChannelMerchantDistribution merchantDistribution = this.getOne(Wrappers.<ChannelMerchantDistribution>lambdaQuery().eq(ChannelMerchantDistribution::getMerId, merId));
        if(merchantDistribution == null){
            merchantDistribution = new ChannelMerchantDistribution();
            BeanUtils.copyProperties(request,merchantDistribution);
            merchantDistribution.setMerId(merId);

            this.save(merchantDistribution);

        }else {
            BeanUtils.copyProperties(request,merchantDistribution);
            this.updateById(merchantDistribution);

        }
        return true;
    }

    @Override
    public DistributionResponse getDistribution(Integer merId) {
        ChannelMerchantDistribution distribution = this.getOne(Wrappers.<ChannelMerchantDistribution>lambdaQuery().eq(ChannelMerchantDistribution::getMerId, merId));
        DistributionResponse response = new DistributionResponse();
        if(Objects.isNull(distribution)){
            return response;
        }
        BeanUtils.copyProperties(distribution,response);
        if (Objects.equals(response.getApplyType(),3)) {
            List<Integer> productIds = Arrays.stream(response.getSpecifyGoods().split(",")).mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
            List<StoreProductResponse> storeProductResponses = merStoreProductService.getMerchnatList(productIds, merId,false);
            response.setProducts(storeProductResponses);
        }
        return response;
    }

}
